'''
    Rockaby: a text annotation system
    Copyright 2010 Martin Paul Eve

    This file is part of Rockaby.

    Rockaby is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
    
    Rockaby is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
    
    You should have received a copy of the GNU General Public License
    along with Rockaby.  If not, see <http://www.gnu.org/licenses/>.

'''

from django.shortcuts import render_to_response, get_object_or_404
from rockaby.models import Episode, Character, ReferenceItem, Part, CharactersInEpisode, ReferencesInEpisode
from django.template.defaultfilters import escape
import rockaby.utils
import rockaby.reference
from django.http import Http404

def characterindex(request):
    allCharacters = Character.objects.order_by('name')

    currentList = None
    
    characters_used = {}
    presentation = []

    for aChar in allCharacters:
        theChar = aChar.name[0:1]
        
        if not theChar in characters_used:
            # create a new dictionary inside the presentation list
            currentList = []
            characters_used[theChar] = currentList 
            newdict = {'name': theChar, 'list':currentList}
            presentation.append(newdict)
            
        currentList.append(aChar)
    
    return render_to_response('characterindex.html', {'title': 'Character List',
                                                      'characters':presentation,
                                                      'charactercount': len(allCharacters)})
    
def iteminfo(request, item_name, ref_or_char):
    characters = Character.objects.all()
    index = ReferenceItem.objects.all()
    
    itemsinepisodes = None
    
    if ref_or_char == 'char':
        itemsinepisodes = CharactersInEpisode.objects.filter(character__name__iexact=item_name)
    else:
        itemsinepisodes = ReferencesInEpisode.objects.filter(reference__name__iexact=item_name)
    
    if len(itemsinepisodes) == 0:
        raise Http404
    
    item = None
    
    if ref_or_char == 'char':
        item = itemsinepisodes[0].character
    else:
        item = itemsinepisodes[0].reference
    
    # technically, this should probably be done through the template
    # however, before changing bear in mind:
    # 1.) Order -- the styling and linking must be done before referencing
    # 2.) Location -- the ref table and the links have to go into two areas, but we don't want to generate twice 
    
    itemInfo = escape(item.information.replace('\r\n','\n'))
    itemInfo = rockaby.utils.utils.applystyle(itemInfo)
    itemInfo = rockaby.utils.utils.styleCharacters(characters, itemInfo)
    itemInfo = rockaby.utils.utils.styleIndex(index, itemInfo)
    
    ReferenceEngine = rockaby.reference.ReferenceEngine(itemInfo)
    itemInfo = ReferenceEngine.referencetext
    
    episodes_used = {}
    presentation = []
    
    for itemsepinfo in itemsinepisodes:
        if not itemsepinfo.episode.part in episodes_used:
            episodes_used[itemsepinfo.episode.part] = []
        episodes_used[itemsepinfo.episode.part].append(itemsepinfo.episode)
            
    # episodes_used is now a dict of {part : episode}
    # now needs to be reformatted
    
    for key in episodes_used:
        newdict = {'part': key, 'episodes': episodes_used[key]}
        presentation.append(newdict)
        
    if ref_or_char == 'char':
        return render_to_response('iteminfo.html', {'title': 'Character ' + item_name,
                                                          'itemname': item_name,
                                                          'iteminformation':itemInfo,
                                                          'references': ReferenceEngine.referencetable,
                                                          'iteminfo': itemsinepisodes,
                                                          'episodes_used': presentation,
                                                          })
    else:
        return render_to_response('iteminfo.html', {'title': 'Reference Item ' + item_name,
                                                          'itemname': item_name,
                                                          'iteminformation':itemInfo,
                                                          'references': ReferenceEngine.referencetable,
                                                          'iteminfo': itemsinepisodes,
                                                          'episodes_used': presentation,
                                                          })

def episodecharacters(request, part_name, episode_id):
    charactersinepisode = CharactersInEpisode.objects.filter(episode__part__name__iexact=part_name, episode__episode=episode_id).order_by('character__name')

    return render_to_response('episodecharacters.html', {'characters':charactersinepisode,})

def episodeindex(request):
    episodes = Episode.objects.all().order_by('part__part_number', 'episode')
    parts = Part.objects.all().order_by('part_number')
    
    partlist = []

    current_position = 0

    for part in parts:
        partdict = {'part': part, 'episodes': []}
        partdict['part'] = part
        
        for counter in range(current_position, len(episodes)):
            episode = episodes[counter]
            if episode.part == part:
                partdict['episodes'].append(episode)
            else:
                current_position = counter
                break
        
        partlist.append(partdict)
    
    return render_to_response('episodeindex.html', {'parts': partlist})

def episodereference(request, part_name, episode_id):
    referencesinepisode = ReferencesInEpisode.objects.filter(episode__part__name__iexact=part_name, episode__episode=episode_id).order_by('reference__name')

    return render_to_response('episodereference.html', {'references':referencesinepisode,})

def episodesynopsis(request, part_name, episode_id):
        
    # get an episode object
    episode = get_object_or_404(Episode, part__name__iexact=part_name, episode=episode_id)

    return render_to_response('episodesynopsis.html', 
                              {'part_name': episode.part.name, 
                               'part_name_title': episode.part.name,
                               'episode_number': episode.episode,
                               'episode_setting': episode.setting,
                               'synopsis_text': episode.synopsis_generated,
                               'references': episode.synopsis_reftable_generated,
                               'title': 'Synopsis of ' + episode.part.name + ' Episode ' + str(episode.episode)})
    
def homepage(request):
    return render_to_response('homepage.html', {})    

def partinfo(request, part_name):
    part_id = rockaby.parts.Parts.PartLookupSanitized[part_name]
        
    # get an episode object
    part = get_object_or_404(GrRefParts, part_number=part_id)
    
    # get all characters and index items from database
    characters = Character.objects.all()
    index = ReferenceItem.objects.all()
    
    part_title = rockaby.parts.Parts.FormattedPartNames[part_id]
    
    partinfotext = '<h3><span>Title</span></h3>\
    <p class="p1"><span>' + part_title + '</span></p>\
    <p class="p1"><span><a href="javascript:back()" title="Go Back">&lt;&lt;&lt; go back</a></span></p>\
    <h3><span>Epigraph</span></h3>\
    <p class="p1"><span>' + part.epigraph + '</span></p>\
    <p class="p1"><span><a href="javascript:back()" title="Go Back">&lt;&lt;&lt; go back</a></span></p>\
    <h3><span>Structure</span></h3>\
    <p class="p1"><span>' + part.structure + '</span></p>\
    <p class="p1"><span><a href="javascript:back()" title="Go Back">&lt;&lt;&lt; go back</a></span></p>'
    
    partinfotext = rockaby.utils.utils.applystyle(partinfotext)
    partinfotext = rockaby.utils.utils.styleCharacters(characters, partinfotext)
    partinfotext = rockaby.utils.utils.styleIndex(index, partinfotext)
    
    ReferenceEngine = rockaby.reference.ReferenceEngine(partinfotext)
    partinfotext = ReferenceEngine.referencetext
    
    return render_to_response('partinfo.html',
                              {'title': part_title, 
                               'partinfo': partinfotext,
                               'references': ReferenceEngine.referencetable,
                               })
    

def referenceindex(request):
    allReferences = ReferenceItem.objects.order_by('name')

    currentList = None
    
    references_used = {}
    presentation = []

    for aRef in allReferences:
        theChar = aRef.name[0:1]
        
        if not theChar in references_used:
            # create a new dictionary inside the presentation list
            currentList = []
            references_used[theChar] = currentList 
            newdict = {'name': theChar, 'list':currentList}
            presentation.append(newdict)
            
        currentList.append(aRef)
    
    return render_to_response('referenceindex.html', {'title': 'Character List',
                                                      'references':presentation,
                                                      'referencecount': len(allReferences)})
    